package pers.whj.handler;

public class Message {
    public int what;
    public int arg1;
    public int arg2;
    public Object obj;
    //use message pool
    private static final Object POOL_LOCK = new Object();
    private static final int MAX_POOL_SIZE = 50;
    private static int sPoolSize = 0;
    private static Message sPool;

    protected long when;
    protected Handler target;
    protected Runnable callback;
    protected Message next;

    public Message() {
    }

    public static Message obtain(Handler target) {
        Message msg = obtain();
        msg.target = target;
        return msg;
    }

    public static Message obtain(Handler target, int what) {
        Message msg = obtain();
        msg.target = target;
        msg.what = what;
        return msg;
    }

    public static Message obtain(Handler target, int what, int arg1, int arg2, Object obj) {
        Message msg = obtain();
        msg.target = target;
        msg.what = what;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        msg.obj = obj;
        return msg;
    }

    public static Message obtain(Handler target, Runnable callback) {
        Message msg = obtain();
        msg.target = target;
        msg.callback = callback;
        return msg;
    }

    private static Message obtain() {
        synchronized (POOL_LOCK) {
            if (sPool != null) {
                Message msg = sPool;
                sPool = sPool.next;
                msg.next = null;
                sPoolSize--;
                return msg;
            }
        }
        return new Message();
    }

    public void recycleUnchecked() {
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        target = null;
        callback = null;
        next = null;
        synchronized (POOL_LOCK) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        long now = System.currentTimeMillis();
        builder.append("{ when=")
                .append((when - now))
                .append(", what=")
                .append(what)
                .append(", arg1=")
                .append(arg1)
                .append(", arg2=")
                .append(arg2)
                .append(", obj=")
                .append(obj)
                .append(" }");
        return builder.toString();
    }
}